


//
//  RFLicensedDebugSettingViewController.m
//  RFIXE2ETestHost
//
//  Created by bill bai on 2025/3/4.
//  Copyright © 2025 Tencent. All rights reserved.
//

#import "RFLicensedDebugSettingViewController.h"

#import "RFIX/RFIXForTest.h"

NSString * const kRFIsLicensedDebugModeKey = @"kRFIsLicensedDebugModeKey";
NSString * const kRFLicensedDebugTaskIDKey = @"kRFLicensedDebugTaskIDKey";


@interface RFLicensedDebugSettingViewController ()
@property (nonatomic, strong) UITextField *taskIDTextField;
@end

@implementation RFLicensedDebugSettingViewController

+ (NSString *)formatDebugInfoString:(NSDictionary *)taskInfo {
  NSMutableString *taskInfoString = [NSMutableString string];
  NSString *taskID = taskInfo[@"taskID"];
  if (taskID) {
    [taskInfoString appendFormat:@"当前调试任务ID: %@\n", taskID];
  }
  NSNumber *success = taskInfo[@"success"];
  if (success) {
    [taskInfoString appendFormat:@"任务%@\n", success.boolValue ? @"成功" : @"失败"];
  }
  NSError *error = taskInfo[@"error"];
  if (error) {
    [taskInfoString appendFormat:@"错误信息: %ld %@\n", (long)error.code, error.localizedDescription];
  }
  
  NSNumber *loadResultCode = taskInfo[@"loadResultCode"];
  if (loadResultCode) {
    if (loadResultCode.integerValue == 0) {
      [taskInfoString appendString:@"加载成功\n"];
    } else if (loadResultCode.integerValue == 15) {
      [taskInfoString appendString:@"加载失败, 存在未注册的 C 函数/全局变量\n"];
    } else {
      [taskInfoString appendFormat:@"加载结果错误码: %ld\n", (long)loadResultCode.integerValue];
    }
  }
  
  NSString *extraMessage = taskInfo[@"extraMessage"];
  if (extraMessage) {
    [taskInfoString appendFormat:@"%@\n", extraMessage];
  }
  
  return [taskInfoString copy];
}

- (void)viewDidLoad {
  [super viewDidLoad];
  
  if (@available(iOS 13.0, *)) {
    self.view.backgroundColor = [UIColor systemBackgroundColor];
  } else {
    self.view.backgroundColor = [UIColor whiteColor];
  }
  
  self.navigationItem.title = @"Debug Setting";
  const CGFloat kScreenWidth = [UIScreen mainScreen].bounds.size.width;
  const CGFloat kHorizontalMargin = 20;
  const CGFloat kTopMargin = 100;
  const CGFloat kVerticalGapSpace = 50;
  
  UILabel *nextLaunchLicensedDebugLabel = [[UILabel alloc] initWithFrame:CGRectMake(kHorizontalMargin,
                                                                                    kTopMargin,
                                                                                    kScreenWidth - 2 * kHorizontalMargin,
                                                                                    50)];
  nextLaunchLicensedDebugLabel.textAlignment = NSTextAlignmentLeft;
  nextLaunchLicensedDebugLabel.text = @"下次启动时开启调试：";
  [self.view addSubview:nextLaunchLicensedDebugLabel];
  CGSize labelSize = [nextLaunchLicensedDebugLabel.text sizeWithAttributes:@{NSFontAttributeName: nextLaunchLicensedDebugLabel.font}];
  
  const BOOL nextLaunchLicensedDebugMode = [[NSUserDefaults standardUserDefaults] boolForKey:kRFIsLicensedDebugModeKey];
  UISwitch *licensedDebugSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(kHorizontalMargin + labelSize.width + 10,
                                                                             kTopMargin + 10,
                                                                             100,
                                                                             50)];
  licensedDebugSwitch.on = nextLaunchLicensedDebugMode;
  [self.view addSubview:licensedDebugSwitch];
  [licensedDebugSwitch addTarget:self action:@selector(licensedDebugSwitchValueChanged:)
                forControlEvents:UIControlEventValueChanged];
  
  
  UILabel *taskIDLabel = [[UILabel alloc] initWithFrame:CGRectMake(kHorizontalMargin,
                                                                   kTopMargin + 1 * kVerticalGapSpace,
                                                                   kScreenWidth - 2 * kHorizontalMargin,
                                                                   50)];
  taskIDLabel.textAlignment = NSTextAlignmentLeft;
  taskIDLabel.text = @"下次启动时调试任务ID：";
  const CGSize taskIDLabelSize = [taskIDLabel.text sizeWithAttributes:@{NSFontAttributeName: taskIDLabel.font}];
  [self.view addSubview:taskIDLabel];
  UITextField *taskIDTextField = [[UITextField alloc] initWithFrame:CGRectMake(kHorizontalMargin + taskIDLabelSize.width + 10,
                                                                               kTopMargin + 1 * kVerticalGapSpace + 5,
                                                                               kScreenWidth - taskIDLabelSize.width - 2 * kHorizontalMargin - 10,
                                                                               40)];
  taskIDTextField.borderStyle = UITextBorderStyleRoundedRect;
  taskIDTextField.keyboardType = UIKeyboardTypeNumberPad;
  [self.view addSubview:taskIDTextField];
  [taskIDTextField addTarget:self action:@selector(taskIDTextFieldValueChanged:) forControlEvents:UIControlEventEditingDidEnd];
  self.taskIDTextField = taskIDTextField;
  [self updateTaskIDTextFieldWithNextLaunchLicensedDebugMode:nextLaunchLicensedDebugMode];
#if RFIX_BUILD_CONFIG_IS_LICENSED
  const BOOL currentLicensedDebugMode = RFIXLicensedDebugModeIsEnabled();
#else
  const BOOL currentLicensedDebugMode = NO;
#endif
  UILabel *licensedDebugLabel = [[UILabel alloc] initWithFrame:CGRectMake(kHorizontalMargin,
                                                                          kTopMargin + 2 * kVerticalGapSpace,
                                                                          kScreenWidth - 2 * kHorizontalMargin,
                                                                          50)];
  licensedDebugLabel.textAlignment = NSTextAlignmentLeft;
  if (currentLicensedDebugMode) {
    licensedDebugLabel.text = @"🟢当前调试模式已【开启】";
  } else {
    licensedDebugLabel.text = @"🔴当前调试模式已【关闭】";
  }
  [self.view addSubview:licensedDebugLabel];
  
#if RFIX_BUILD_CONFIG_IS_LICENSED
  NSDictionary *currentTaskInfo = RFIXGetLicensedDebugTaskInfo();
#else
  NSDictionary *currentTaskInfo = nil;
#endif  // RFIX_BUILD_CONFIG_IS_LICENSED
  if (currentTaskInfo) {
    NSString *taskInfoString = [[self class] formatDebugInfoString:currentTaskInfo];
    // adjust the height of taskInfoLabel
    UILabel *taskInfoLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    CGSize taskInfoLabelSize = [taskInfoString boundingRectWithSize:CGSizeMake(kScreenWidth - 2 * kHorizontalMargin, CGFLOAT_MAX)
                                                            options:NSStringDrawingUsesLineFragmentOrigin
                                                         attributes:@{NSFontAttributeName: taskInfoLabel.font}
                                                            context:nil].size;
    taskInfoLabel.frame = CGRectMake(kHorizontalMargin,
                                     kTopMargin + 3 * kVerticalGapSpace,
                                     kScreenWidth - 2 * kHorizontalMargin,
                                     taskInfoLabelSize.height);
    
    taskInfoLabel.textAlignment = NSTextAlignmentLeft;
    taskInfoLabel.numberOfLines = 0;
    taskInfoLabel.text = taskInfoString;
    [self.view addSubview:taskInfoLabel];
  }
  
  // add a done button to dismiss the keyboard
  UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                                                              target:self
                                                                              action:@selector(dismissKeyboard)];
  self.navigationItem.rightBarButtonItem = doneButton;
}

- (void)dismissKeyboard {
  [self.taskIDTextField resignFirstResponder];
}

- (void)updateTaskIDTextFieldWithNextLaunchLicensedDebugMode:(BOOL)nextLaunchLicensedDebugMode {
  self.taskIDTextField.enabled = nextLaunchLicensedDebugMode;
  if (!nextLaunchLicensedDebugMode) {
    self.taskIDTextField.text = @"";
    self.taskIDTextField.placeholder = @"请先开启调试模式";
  } else {
    NSString *taskID = [[NSUserDefaults standardUserDefaults] stringForKey:kRFLicensedDebugTaskIDKey];
    self.taskIDTextField.text = taskID;
    self.taskIDTextField.placeholder = @"请输入任务ID";
  }
}


- (void)licensedDebugSwitchValueChanged:(UISwitch *)licensedDebugSwitch {
  const BOOL isLicensedDebugMode = licensedDebugSwitch.isOn;
  [[NSUserDefaults standardUserDefaults] setBool:isLicensedDebugMode forKey:kRFIsLicensedDebugModeKey];
  [[NSUserDefaults standardUserDefaults] synchronize];
  NSLog(@"下次启动调试模式将会 【%@】", isLicensedDebugMode ? @"开启" : @"关闭");
  
  [self updateTaskIDTextFieldWithNextLaunchLicensedDebugMode:isLicensedDebugMode];
}

- (void)taskIDTextFieldValueChanged:(UITextField *)textField {
  NSString *taskID = textField.text;
  [[NSUserDefaults standardUserDefaults] setObject:taskID forKey:kRFLicensedDebugTaskIDKey];
  [[NSUserDefaults standardUserDefaults] synchronize];
  NSLog(@"下次启动调试任务ID为：%@", taskID);
}

@end
